﻿using STT.Business;
using STT.Entities;
using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using STT.Layer.Connection;
using System.Collections.Generic;

namespace STT.Admin.UserControls
{
    public partial class ucThemHocVien : System.Web.UI.UserControl
    {
        ToolBox tbx = new ToolBox();
        public static DataTable tbStatic;
        string Ma_HV = "";
        string DonVi, MaDanToc, MaNhomNL, TenDanToc;
        int MaDonVi;
        bool KTGiamDoc = true;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = BTbGiangVien.GiangVien_LayDonVi(new ETbGiangVien
            {
                MaGV = Session["TenDN"].ToString()
            });
            MaDonVi = Int32.Parse(dt.Rows[0][0].ToString()); 

            DataTable DV = BTbDonVi.SelectAll();
            
            for (int k = 0; k < DV.Rows.Count; k++)
            {
                if (MaDonVi.ToString().Trim() == DV.Rows[k][0].ToString().ToLower().Trim())
                {
                    DonVi = DV.Rows[k][0].ToString();
                    break;
                }
            }
                LoadDropDownList();
               
                if (!IsPostBack)
                {
                    Methods.NhomNL(ref ddlNhomNL);
                    //LoadThemSua();

                    
                }
                Methods.MaNgachLuong(ref ddlMaNL);
                Methods.HeSoLuong(ref ddlHeSL);
                if (tbStatic == null)
                {
                    tbStatic = new DataTable();
                    tbStatic.Columns.Add("MaNgoaiNgu", typeof(int));
                    tbStatic.Columns.Add("NgayCap", typeof(DateTime));
                    tbStatic.Columns.Add("NoiCap", typeof(string));
                    tbStatic.Columns.Add("TenDN", typeof(string));
                }

                btThemMoi.Visible = true;
                btSua.Visible = false;
                //ddlDonVi.SelectedValue = MaDonVi.ToString();
                //ThongBao(ddlDonVi.SelectedValue);
                if (Request.QueryString["idhv"] != null && Request.QueryString["idhv"].ToString().Trim() != "")
                {
                    //try
                    //{
                    // An nut them moi
                    btThemMoi.Visible = false;
                    btSua.Visible = true;
                    ddlMaNL.Enabled = true;
                    ddlHeSL.Enabled = true;
                    // Lay ma giang vien
                    Ma_HV = Request.QueryString["idhv"].ToString().Trim();

                    ETbHocVien hv = BTbHocVien.SelectByMaHV(Ma_HV);
                    DataTable dantoc = BTbDanToc.SelectAll1();
                    DataTable MaNL = BTbMaNgachLuong.SelectAll();
                    hvNgoaiNgu.DataSource = BTbHocVien_NgoaiNgu.SelectByMaHV(Ma_HV);
                    hvNgoaiNgu.DataBind();
                    txtTenHV.Text = hv.TenHV;
                    txtTen.Text = hv.Ten;
                    txtDiaChi.Text = hv.DiaChi;
                    txtQueQuan.Text = hv.QueQuan;
                    txtNoiCap.Text = hv.NoiCapCMT;
                    txtSDT.Text = hv.Sdt;
                    ddlChucVu.SelectedValue = hv.ChucVu.ToString();
                    ddlDonVi.SelectedValue = hv.MaDonVi.ToString();
                    //ThongBao(hv.MaDonVi.ToString());
                    // doan nay la sao day
                    ddlPhongBan.SelectedValue = hv.PhongBan.ToString().Trim() == "" ? "-1" : hv.PhongBan.ToString();
                    txtNgaySinh.Text = hv.NgaySinh.ToString("yyyy-MM-dd");
                    if (hv.DanToc == null)
                    {
                        ddlDanToc.SelectedValue = "-1";
                    }
                    else
                    {
                        for (int j = 0; j < dantoc.Rows.Count; j++)
                        {
                            if (hv.DanToc.ToString().ToLower().Trim() == dantoc.Rows[j][1].ToString().ToLower().Trim())
                            {
                                MaDanToc = dantoc.Rows[j][0].ToString().ToLower().Trim();
                                break;
                            }
                            else
                            {
                                MaDanToc = "-1";
                            }
                        }
                        ddlDanToc.SelectedValue = MaDanToc;
                    }
                    if (hv.MaNgachLuong == null)
                    {
                        ddlMaNL.SelectedValue = "-1";
                    }
                    else
                    {
                        ddlMaNL.SelectedValue = hv.MaNgachLuong.ToString().TrimEnd();
                    }
                    for (int k = 0; k < MaNL.Rows.Count; k++)
                    {
                        MaNhomNL = null;
                        if (hv.MaNgachLuong == null)
                        {
                            ddlNhomNL.SelectedValue = "-1";
                        }
                        else
                        {
                            if (hv.MaNgachLuong.ToString().Trim() == MaNL.Rows[k][0].ToString().Trim())
                            {
                                ddlNhomNL.SelectedValue = MaNL.Rows[k][2].ToString().Trim();
                                break;
                            }
                            else
                            {
                                ddlNhomNL.SelectedValue = "-1";
                            }
                        }

                    }
                    
                    if (hv.HeSoLuong.ToString() == "0")
                    {
                        ddlHeSL.SelectedValue = "-1";
                    }
                    else
                    {
                        ddlHeSL.SelectedValue = hv.HeSoLuong.ToString().TrimEnd();
                    }
                    ddlGioiTinh.SelectedValue = hv.GioiTinh == null ? "-1" : hv.GioiTinh.TrimEnd();
                    txtSoCMT.Text = hv.SoCMT;
                    txtNgayCap.Text = hv.NgayCapCMT.ToString("yyyy-MM-dd");
                    txtNoiCap.Text = hv.NoiCapCMT;
                    ddlTDVanHoa.SelectedValue = hv.TDVanHoa.ToString().Trim() == "0" ? "-1" : hv.TDVanHoa.ToString();

                    ddTrinhDo.SelectedValue = hv.TrinhDo.ToString().Trim() == "0" ? "-1" : hv.TrinhDo.ToString();
                    ddLopHoc.SelectedValue = hv.MaLop.ToString().Trim() == "" ? "-1" : hv.MaLop.ToString();

                    txtQueQuan.Text = hv.QueQuan;

                    if (hv.Anh == null)
                    {
                        anhDaiDien.ImageUrl = "~/Uploads/Avatar/avatar-default.jpg";
                    }
                    else
                    {
                        anhDaiDien.ImageUrl = "~/Uploads/Avatar/" + hv.Anh;
                        imgAnhDaiDienCu.Value = hv.Anh;
                    }

                    txtHieuChinhThanNhan.Text = hv.HieuTrinhThanNhan;
                    txtGhiChu.Text = hv.GhiChu;

                    //}
                    //catch { }
                }
                else
                {
                    hvNgoaiNgu.DataSource = tbStatic;
                    hvNgoaiNgu.DataBind();
                }
                //Methods.HeSoLuong_LoadDropDownList(ref ddlHeSL, Int32.Parse(ddlNhomNL.SelectedValue));
                //Methods.MaNgachLuong_LoadDropDownList(ref ddlMaNL, Int32.Parse(ddlNhomNL.SelectedValue));
                
        }
        protected void LoadThemSua()
        {
            
        }
        bool KiemTraGiamDoc()
        {
            return BTbHocVien.KiemTraGiamDoc(new ETbHocVien
                {
                    MaDonVi = MaDonVi
                });
        }
        bool KiemTraDuLieu()
        {
            return BTbHocVien.KiemTraDuLieu(new ETbHocVien
            {
               MaHV = Ma_HV,
                SoCMT = txtSoCMT.Text
            });
        }
        void LoadNgoaiNguHocVien()
        {
            hvNgoaiNgu.AutoGenerateColumns = false;
            hvNgoaiNgu.DataSource = BTbHocVien_NgoaiNgu.SelectByMaHV(Ma_HV);
            hvNgoaiNgu.DataBind();
        }


        void LoadDropDownList()
        {
            Methods.ChucVu(ref ddlChucVu);
            Methods.PhongBan(ref ddlPhongBan);
            Methods.HocVan(ref ddlTDVanHoa);
            Methods.ChuyenMon(ref ddTrinhDo);
            Methods.DanToc(ref ddlDanToc);
            //Methods.SortDDL(ref ddlDanToc);
            
            Methods.DonViHocVien(ref ddlDonVi);

            //ThongBao(ddlDanToc.FindByText("---------Chọn---------").ToString());
            //Methods.NgoaiNgu(ref cbNgoaiNgu);
            //Methods.Lop(ref ddLopHoc);
            ddLopHoc.DataSource = tbx.GetDataTableByNguoiTao("TbLop_SelectAll", Session["TenDN"].ToString());
            ddLopHoc.DataTextField = "TenLop";
            ddLopHoc.DataValueField = "MaLop";
            ddLopHoc.DataBind();

            //Methods.DonViHocVien(ref ddlDonVi);

            hvNgoaiNgu.DataSource = BTbGiangVien_NgoaiNgu.SelectTop(0);
            hvNgoaiNgu.DataBind();
        }

        protected void gvNgoaiNgu_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int MaNN = int.Parse(hvNgoaiNgu.DataKeys[e.RowIndex].Value.ToString());

            if (Ma_HV == "")
            {
                DataRow[] rows;
                rows = tbStatic.Select("MaNgoaiNgu=" + MaNN + " AND TenDN='" + Session["TenDN"].ToString() + "'");

                foreach (DataRow r in rows)
                    r.Delete();

                hvNgoaiNgu.DataSource = tbStatic;
                hvNgoaiNgu.DataBind();
            }
            else
            {
                BTbHocVien_NgoaiNgu.Delete(Ma_HV, MaNN);
                LoadNgoaiNguHocVien();
            }
        }

        protected void hvNgoaiNgu_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DropDownList dd = e.Row.FindControl("ddlTenNgoaiNgu") as DropDownList;

            if (dd != null)
                Methods.NgoaiNgu(ref dd);

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                dd.SelectedValue = DataBinder.Eval(e.Row.DataItem, "MaNgoaiNgu").ToString();
            }
        }

        protected void btThemMoiNgoaiNgu_Click(object sender, EventArgs e)
        {
            Control control = null;
            if (hvNgoaiNgu.FooterRow != null)
            {
                control = hvNgoaiNgu.FooterRow;
            }
            else
            {
                control = ((Control)sender).Parent;
            }

            DropDownList ddlTen = (DropDownList)control.FindControl("ddlTenNgoaiNgu");
            TextBox txtNgay = (TextBox)control.FindControl("txtNgayCap");
            TextBox txtNoi = (TextBox)control.FindControl("txtNoiCap");

            if (Ma_HV == "")
            {
                if (tbStatic.Rows.Count > 0)
                {
                    DataRow[] rows;
                    rows = tbStatic.Select("MaNgoaiNgu=" + ddlTen.SelectedValue.TrimEnd() + "' AND TenDN='" + Session["TenDN"].ToString() + "'");

                    if (rows.Length > 0)
                    {
                        ThongBao("Đã tồn tại ngoại ngữ.");
                        return;
                    }
                }

                DataRow row = tbStatic.NewRow();
                row["MaNgoaiNgu"] = ddlTen.SelectedValue;
                row["NgayCap"] = DateTime.Parse(txtNgay.Text);
                row["NoiCap"] = txtNoi.Text;
                row["TenDN"] = Session["TenDN"].ToString();

                tbStatic.Rows.Add(row);

                hvNgoaiNgu.DataSource = tbStatic;
                hvNgoaiNgu.DataBind();
            }
            else
            {
                // Kiem tra su ton tai ngoai ngu
                try
                {
                    // Them moi ngoai ngu
                    BTbHocVien_NgoaiNgu.Insert(new ETbHocVien_NgoaiNgu
                    {
                        MaHV = Ma_HV,
                        NgayCap = DateTime.Parse(txtNgay.Text),
                        MaNgoaiNgu = int.Parse(ddlTen.SelectedValue),
                        NoiCap = txtNoi.Text,
                        // TrangThai = 1
                    });

                    LoadNgoaiNguHocVien();
                    Session["action"] = 1;
                }
                catch
                { ThongBao("Đã tồn tại ngoại ngữ."); }
            }
        }

        protected void btSua_Click(object sender, EventArgs e)
        {
            string id = "";

            if (upAnhDaiDien.HasFile)
            {
                try
                {
                    File.Delete(Path.Combine(Server.MapPath("~/Uploads/Avatar/") + imgAnhDaiDienCu.Value));
                }
                catch
                { }

                id = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString() + "¿" + upAnhDaiDien.FileName;
                upAnhDaiDien.SaveAs(Path.Combine(Server.MapPath("~/Uploads/Avatar/"), id));
            }
            else
                id = imgAnhDaiDienCu.Value;
            DataTable LayGiamDoc = BTbHocVien.LayGiamDoc(new ETbHocVien { MaDonVi = MaDonVi });
            if(KiemTraGiamDoc() && ddlChucVu.SelectedItem.Text.ToString().ToLower().Trim() == "giám đốc" && LayGiamDoc.Rows[0][0].ToString().ToLower().Trim() != Ma_HV)
            {
                KTGiamDoc = true;
            }
            else 
            {
                KTGiamDoc = false;
            }
            if(!KTGiamDoc)
            {
                BTbHocVien.Update(new ETbHocVien
                {
                    MaHV = Ma_HV,
                    TenHV = txtTenHV.Text,
                    Ten = txtTen.Text,
                    GioiTinh = ddlGioiTinh.SelectedItem.Text,
                    ChucVu = int.Parse(ddlChucVu.SelectedValue),
                    PhongBan = Int32.Parse(ddlPhongBan.SelectedValue),
                    NgaySinh = DateTime.Parse(txtNgaySinh.Text),
                    DanToc = ddlDanToc.SelectedItem.Text,
                    MaNgachLuong = ddlMaNL.SelectedValue,
                    HeSoLuong = Double.Parse(ddlHeSL.SelectedValue),
                    SoCMT = txtSoCMT.Text,
                    NgayCapCMT = DateTime.Parse(txtNgayCap.Text),
                    NoiCapCMT = txtNoiCap.Text,
                    TDVanHoa = Int32.Parse(ddlTDVanHoa.SelectedValue),
                    TrinhDo = Int32.Parse(ddTrinhDo.SelectedValue),
                    QueQuan = txtQueQuan.Text,
                    DiaChi = txtDiaChi.Text,
                    Anh = id,
                    HieuTrinhThanNhan = txtHieuChinhThanNhan.Text,
                    Sdt = txtSDT.Text,
                    MaLop = int.Parse(ddLopHoc.SelectedValue),
                    MaDonVi = MaDonVi,
                    GhiChu = txtGhiChu.Text,
                    TrangThaiTB = 0,
                    Loai = 0,
                    NguoiTao = Session["TenDN"].ToString()
                });
            }
            else
            {
                ThongBao("Chức vụ giám đốc của học viên này thuộc đơn vị " + MaDonVi + " đã tồn tại!");
            }
            Session["action"] = 2;
            Response.Redirect("~/Admin/Default.aspx?idpage=qldshv", true);
        }

        protected void btThemMoi_Click(object sender, EventArgs e)
        {
            if (!KiemTraDuLieu())
            {
                if(KiemTraGiamDoc() && ddlChucVu.SelectedItem.Text.ToLower().Trim() =="giám đốc")
                {
                    ThongBao("Chức vụ giám đốc của học viên này thuộc đơn vị " + MaDonVi + " đã tồn tại!");
                }
                else
                {
                    string id = "";
                    if (upAnhDaiDien.HasFile)
                    {
                        id = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString() + "¿" + upAnhDaiDien.FileName;
                        upAnhDaiDien.SaveAs(Path.Combine(Server.MapPath("~/Uploads/Avatar/"), id));
                    }
                    DataTable dantoc = BTbDanToc.SelectAll1();
                    for (int j = 0; j < dantoc.Rows.Count; j++)
                    {
                        //ThongBao(dantoc.Rows[j][0].ToString());
                        if (ddlDanToc.SelectedValue.Trim() == dantoc.Rows[j][0].ToString().Trim())
                        {
                            TenDanToc = dantoc.Rows[j][1].ToString().Trim();
                            break;
                        }
                    }
                    //ThongBao(ddlDanToc.Text);
                    string MaHV = tbx.GetID("TbHocVien", "MaHV", "HV");
                    BTbHocVien.Insert1(new ETbHocVien
                    {
                        MaHV = MaHV,
                        TenHV = txtTenHV.Text,
                        Ten = txtTen.Text,

                        GioiTinh = ddlGioiTinh.SelectedItem.Text,
                        ChucVu = Int32.Parse(ddlChucVu.SelectedValue),
                        PhongBan = Int32.Parse(ddlPhongBan.SelectedValue),
                        NgaySinh = DateTime.Parse(txtNgaySinh.Text),
                        DanToc = ddlDanToc.SelectedItem.Text,// chay
                        MaNgachLuong = ddlMaNL.SelectedValue,
                        HeSoLuong = Double.Parse(ddlHeSL.SelectedValue),
                        SoCMT = txtSoCMT.Text,
                        NgayCapCMT = DateTime.Parse(txtNgayCap.Text),
                        NoiCapCMT = txtNoiCap.Text,
                        TDVanHoa = Int32.Parse(ddlTDVanHoa.SelectedValue),
                        TrinhDo = Int32.Parse(ddTrinhDo.SelectedValue),
                        QueQuan = txtQueQuan.Text,
                        DiaChi = txtDiaChi.Text,
                        Anh = id,
                        HieuTrinhThanNhan = txtHieuChinhThanNhan.Text,
                        Sdt = txtSDT.Text,
                        MaLop = int.Parse(ddLopHoc.SelectedValue),
                        MaDonVi = Int32.Parse(ddlDonVi.SelectedValue),
                        GhiChu = txtGhiChu.Text,
                        TrangThaiTB = 0,
                        Loai = 0,
                        NguoiTao = Session["TenDN"].ToString()

                    });

                    // Them bang giang vien ngoai ngu
                    DataRow[] tb = tbStatic.Select("TenDN='" + Session["TenDN"].ToString() + "'");

                    int count = tb.Length;
                    if (count > 0)
                    {
                        for (int i = 0; i < count; i++)
                        {
                            BTbHocVien_NgoaiNgu.Insert(new ETbHocVien_NgoaiNgu
                            {
                                MaHV = MaHV,
                                MaNgoaiNgu = int.Parse(tb[i]["MaNgoaiNgu"].ToString()),
                                NgayCap = DateTime.Parse(tb[i]["NgayCap"].ToString()),
                                NoiCap = tb[i]["NoiCap"].ToString(),
                            });

                            // Xoa sau khi them
                            tb[i].Delete();
                        }
                    }

                    // Tao tai khoan cho hoc vien
                    BTbDangNhap dn = new BTbDangNhap();

                    BTbDangNhap.Insert(new ETbDangNhap
                    {
                        TenDangNhap = MaHV,
                        MatKhau = dn.GetMD5("12345678"+dn.Radomchar()),
                        Quyen = "4",
                        RadomPass = dn.Radomchar(),
                        KhoaTaiKhoan = 0
                    });

                    Session["action"] = 1;
                    Response.Redirect("~/Admin/Default.aspx?idpage=qldshv", true);
                }
            }
            else
            {
                ThongBao("Học viên này đã tồn tại!");
            }
        }

        void ThongBao(string Loi)
        {
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!", "<script>alert('" + Loi + "')</script>", false);
        }

        protected void ddlNhomNL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlNhomNL.SelectedValue == "-1")
                {
                    ThongBao("Bạn hãy chọn nhóm ngạch lương...!");

                }
                else
                {
                    ddlMaNL.Enabled = true;
                    ddlHeSL.Enabled = true;
                    //ThongBao(ddlNhomNL.SelectedValue);
                    Methods.HeSoLuong_LoadDropDownList(ref ddlHeSL, Int32.Parse(ddlNhomNL.SelectedValue));
                    Methods.MaNgachLuong_LoadDropDownList(ref ddlMaNL, Int32.Parse(ddlNhomNL.SelectedValue));

                }
            }
            catch (Exception ex)
            {
                Response.Write("");
            }
        }
    }
}